package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // 路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("请求的 URI: {}", request.getRequestURI());

        // 获取本次请求的 URL
        String requestURI = request.getRequestURI();

        // 定义不需要处理的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**", // 后台页面
                "/front/**",    // 前台页面
                "/common/**",
                "/user/sendMsg",
                "/user/login",
        };

        // 检查请求的 URI 是否在白名单中
        boolean check = check(requestURI, urls);
        if (check) {
            log.info("本次请求不需要处理: {}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        // 判断是否已经登录，如果已登录，则放行
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户 ID: {}", request.getSession().getAttribute("employee"));
            Long empId= (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrent(empId);
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("user")  != null) {
            log.info("用户已登录，用户 ID: {}", request.getSession().getAttribute("user"));
            Long userId= (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrent(userId);
            filterChain.doFilter(request, response);
            int arr[] ={1,2,3,4,};

            return;
        }
        // 未登录，返回未登录结果，没有登录不让跳转，是我们在前端定义好的

            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配，判断请求 URI 是否在定义的白名单中
     *
     * @param requestURI 请求的 URI
     * @param urls       白名单路径数组
     * @return 是否匹配
     */
    public boolean check(String requestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }
}